package servlets;

import beans.StuInfoBean;
import utils.ExportExcelUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

public class exportInfoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        if (session.getAttribute("stuList") != null) {
            List<StuInfoBean> list = (List<StuInfoBean>) session.getAttribute("stuList");
            List<String> listName = Arrays.asList("学号", "姓名", "性别", "学校", "电话", "籍贯", "学院", "专业", "班级");

            List<Map<String, String>> students = new ArrayList<>();
            for (StuInfoBean s : list) {
                getInfoToMap(s, students);
            }
            ExportExcelUtil.excelPort(listName, students, response);
        } else if (session.getAttribute("stuInfo") != null) {
            StuInfoBean stu = (StuInfoBean) session.getAttribute("stuInfo");
            List<String> listName = Arrays.asList("学号", "姓名", "性别", "学校", "电话", "籍贯", "学院", "专业", "班级");
            List<Map<String, String>> student = new ArrayList<>();
            getInfoToMap(stu, student);
            ExportExcelUtil.excelPort(listName, student, response);
        } else {
            PrintWriter out = response.getWriter();
            out.write("EXPORT ERROR");
        }
    }

    private void getInfoToMap(StuInfoBean stu, List<Map<String, String>> student) {
        Map<String, String> map = new HashMap<>();
        map.put("学号", stu.getId());
        map.put("姓名", stu.getUsername());
        map.put("性别", stu.getGender());
        map.put("学校", stu.getSchool());
        map.put("电话", stu.getTel());
        map.put("籍贯", stu.getOrigin());
        map.put("学院", stu.getCollege());
        map.put("专业", stu.getMajor());
        map.put("班级", stu.getOfClass());
        student.add(map);
    }
}
